import 'package:pacsun/provider/taskDetailProv.dart';
import 'package:pacsun/provider/taskListProv.dart';
import 'package:pacsun/utils/utils.dart';
import 'package:pacsun/view/task/widgets/howCoypLink.dart';
import 'package:pacsun/view/task/widgets/loadding.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:photo_manager/photo_manager.dart';
import './mediaPickerPage.dart';
import 'package:flutter/material.dart';
import 'package:pacsun/view/task/theme/app_colors.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pacsun/view/task/widgets/cache_network_image.dart';
import 'package:provider/provider.dart';
import 'package:pacsun/model/taskModel.dart';

class TaskFlowSheet extends StatelessWidget {
  const TaskFlowSheet({super.key});

  @override
  Widget build(BuildContext context) {
    // 审核记录
    final taskProv = context.read<TaskDetailProv>();

    List<FlowItem>? auditLogList = taskProv.taskFlows;
    final int currenStatus;
    if (auditLogList != null && auditLogList.isNotEmpty) {
      currenStatus = int.parse(auditLogList[0].status);
    } else {
      currenStatus = 0;
    }
    return Selector<TaskDetailProv, List<AuditLog>>(
      selector: (context, taskDetailModel) =>
          taskDetailModel.auditLogList ?? [],
      builder: (context, auditLogList, child) {
        return SheetContainer(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SheetContainerHeader(
                title: 'Task Review Status',
              ),
              SizedBox(height: 30.h),
              LimitedBox(
                maxHeight: 380.h,
                child: ListView.builder(
                  // shrinkWrap: true,
                  scrollDirection: Axis.vertical,
                  itemCount: auditLogList.length,
                  itemBuilder: (context, index) {
                    return _buildFlowItem(auditLogList[index], currenStatus);
                  },
                ),
              )
            ],
          ),
        );
      },
    );
  }

  Widget _buildFlowItem(AuditLog e, int currenStatus) {
    // Map<String, String> flowStatusStr = {
    //   'CONTENT_PROOF_PENDING_REVIEW': 'Approved',
    //   'CONTENT_PREVIEW_APPROVED': 'Approved',
    //   'CONTENT_UGC_REVIEW_APPROVED': 'Approved',
    //   'CONTENT_UGC_PENDING_PREVIEW': 'Pending',
    //   'BEGINNER_REVIEW_REJECTED': 'Not Approved',
    //   'CONTENT_PREVIEW_REJECTED': 'Not Approved',
    //   'CONTENT_REVIEW_REJECTED': 'Not Approved',
    // };
    // UNDER_REVIEW​（内容审核状态）：
    // 1：表示内容正在审核中（content under review）
    // 2：表示内容已通过（content approved）
    // 3：表示内容未通过（content not approved）
    // ​SHARE_CONTENT​（分享内容状态）：
    // 1：表示需要分享（share）
    // 2：表示分享完成（share done）
    // ​UPLOAD_SCREENSHOT​（上传截图状态）：
    // 1：表示需要上传（upload）
    // 2：表示上传的截图正在审核中（upload under review）
    // 3：表示上传的截图已通过（upload approved）
    // 4：表示上传的截图未通过（upload not approved）
    // ​SUCCESS​（成功状态）：
    // 1：表示奖励审核中（reward under review）
    // 2：表示奖励已通过（reward approved）
    // 3：表示奖励未通过（reward not approved）
    Map<int, String> flowStatusStr = {
      1: 'Pending',
      2: 'Approved',
      3: 'Not Approved',
    };
    final bool isApproved = e.auditStatus.contains('APPROVED') ||
        e.auditStatus.contains('COMPLETED');
    final bool isNotApproved = e.auditStatus.contains('REJECTED');
    final int staus = isApproved
        ? 2
        : isNotApproved
            ? 3
            : 1;
    return Column(
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            CacheNetworkImage(
              imageUrl: e.contentThumbnail,
              width: 40.w,
              height: 40.h,
              borderRadius: 4,
            ),
            SizedBox(
              width: 10.w,
            ),
            _bildFlowCenter(e, isNotApproved),
            _buildFlowStatus(flowStatusStr[staus] ?? ''),
          ],
        ),
        _buildBorderBottom()
      ],
    );
  }

  Widget _bildFlowCenter(AuditLog e, bool isNotApproved) {
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            convertToUSTime(e.createTime, showTime: true),
            style: customTextStyle(opacity: .5),
          ),
          SizedBox(
            height: 4.h,
          ),
          Text(
            e.contentTitle,
            style: customTextStyle(),
          ),
          if (isNotApproved && e.auditRemark.isNotEmpty)
            Container(
              padding: EdgeInsets.all(6).r,
              margin: EdgeInsets.only(top: 3).r,
              decoration: BoxDecoration(
                  color: Color(0XFFFF563F).withAlpha((255 * 0.3).floor()),
                  borderRadius: BorderRadius.circular(4).r),
              child: Text(
                e.auditRemark,
                style: customTextStyle(height: 1.3),
              ),
            )
        ],
      ),
    );
  }

  Widget _buildFlowStatus(String flowState) {
    final Map<String, String> statuIconMap = {
      'Pending': 'assets/icons/icon_task_flow.svg',
      'Approved': 'assets/icons/icon_flow_success.svg',
      'Not Approved': 'assets/icons/icon_flow_error.svg',
    };

    return SizedBox(
      width: 110.w,
      child: Column(
        children: [
          if (flowState.isNotEmpty) ...[
            SvgPicture.asset(
              statuIconMap[flowState] ?? '',
              width: 23.w,
              height: 23.h,
            ),
            const SizedBox(
              height: 5,
            ),
            Text(
              flowState,
              style: customTextStyle(),
            )
          ]
        ],
      ),
    );
  }

  Widget _buildBorderBottom() {
    return Container(
      width: double.infinity,
      height: 1,
      margin: EdgeInsets.symmetric(vertical: 10),
      color: AppColors.flowBorderColor.withAlpha(52),
    );
  }
}

class TaskFlowUploadSheet extends StatelessWidget {
  final String type;
  const TaskFlowUploadSheet({super.key, this.type = 'upload'});
  @override
  Widget build(BuildContext context) {
    final taskDetailProv = Provider.of<TaskDetailProv>(
      context,
      listen: false,
    );
    final taskListProv = context.read<TaskListProv>();

    String platformIconUrl = taskDetailProv.taskDtail?.platformIconUrl ?? '';
    String platformStr = taskDetailProv.taskDtail?.platformStr ?? '';
    ReportData? reportData = taskDetailProv.reportData;

    if (type != 'upload') {
      taskDetailProv.inputController.text = reportData?.contentUrl ?? '';
    }

    void saveAndUpload() async {
      GlobalLoading.show(context, text: 'Uploading...');
      bool res = await taskDetailProv.saveAndUpload();
      GlobalLoading.hide();
      if (res) {
        Fluttertoast.showToast(
          msg: 'Upload Success',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
        );
        taskListProv.refreshCurrentCategory();
        Navigator.of(context).pop();
      } else {
        Fluttertoast.showToast(
          msg: 'Upload Failed',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
        );
      }
    }

    return SheetContainer(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SheetContainerHeader(
            title: 'UPLOAD',
            actions: type == 'upload'
                ? [
                    Selector<TaskDetailProv, bool>(
                      builder: (context, enable, chil) {
                        return SizedBox(
                          width: 75.w,
                          height: 26.w,
                          child: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              backgroundColor: AppColors.shareBtnColor,
                              disabledBackgroundColor:
                                  AppColors.shareBtnColor.withAlpha(78),
                              padding: EdgeInsets.zero,
                            ),
                            onPressed: enable ? saveAndUpload : null,
                            child: Text(
                              'SAVE',
                              style: customTextStyle(
                                fontSize: 14,
                                fontFamily: FontFamily.gilroyBold,
                                opacity: enable ? 1 : 0.3,
                              ),
                            ),
                          ),
                        );
                      },
                      selector: (_, prov) => prov.enable,
                    ),
                  ]
                : [],
          ),
          SizedBox(height: 30.h),
          Text(
            'After sharing the content on social media, paste the link and upload a screenshot of your post to complete the task.',
            style: customTextStyle(fontSize: 14, height: 1.4),
          ),
          SizedBox(height: 20.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  CacheNetworkImage(
                    imageUrl: platformIconUrl,
                    width: 30.w,
                    height: 30.h,
                    borderRadius: 8,
                    imageType: ImageType.asset,
                  ),
                  SizedBox(width: 5.w),
                  Text(
                    'Content Link',
                    style: customTextStyle(fontSize: 14),
                  ),
                ],
              ),
              Spacer(),
              GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => HowCoyplink(platform: platformStr),
                    ),
                  );
                },
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      'How To Copy Link?',
                      style: customTextStyle(opacity: 0.3),
                    ),
                    SizedBox(width: 5.w),
                    SvgPicture.asset(
                      'assets/icons/icon_arrow.svg',
                      width: 12.w,
                      height: 12.h,
                      color: Colors.white.withAlpha(52),
                    ),
                  ],
                ),
              )
            ],
          ),
          Container(
            width: double.infinity,
            height: 52.h,
            margin: EdgeInsets.only(top: 12),
            padding: EdgeInsets.only(right: 20).r,
            decoration: BoxDecoration(
              color: Color(0XFF111111),
              borderRadius: BorderRadius.circular(8).r,
            ),
            child: Row(
              children: [
                Selector<TaskDetailProv, TextEditingController>(
                  selector: (_, prov) => prov.inputController,
                  builder: (context, inputController, child) {
                    return Expanded(
                      child: TextField(
                        cursorColor: AppColors.textFieldCursorColor,
                        style: TextStyle(color: Colors.white),
                        onChanged: taskDetailProv.setContentUrl,
                        controller: inputController,
                        decoration: InputDecoration(
                          hintText: 'Paste the shared link here',
                          hintStyle: customTextStyle(fontSize: 14, opacity: .2),
                          labelStyle: TextStyle(color: Colors.grey),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8).r,
                            borderSide: BorderSide.none,
                          ),
                          contentPadding: EdgeInsets.symmetric(
                              horizontal: 16, vertical: 12),
                        ),
                      ),
                    );
                  },
                ),
                if (type == 'upload')
                  GestureDetector(
                    onTap: taskDetailProv.getCopyValue,
                    child: Container(
                      width: 54.h,
                      height: 23.h,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: Color(0XFFFFFFFF).withAlpha(52),
                        borderRadius: BorderRadius.circular(11.5).r,
                      ),
                      child: Text(
                        'PASTE',
                        style: customTextStyle(),
                      ),
                    ),
                  ),
              ],
            ),
          ),
          Selector<TaskDetailProv, List<UploadModel>>(
            selector: (_, prov) => prov.auditUploadPhotos,
            builder: (context, photos, child) {
              return Container(
                width: 348.w,
                height: 400.h,
                margin: EdgeInsets.only(top: 10).r,
                child: RepaintBoundary(
                  child: GridView.builder(
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      childAspectRatio: 1.0,
                      mainAxisSpacing: 10.r,
                      crossAxisSpacing: 10.r,
                    ),
                    shrinkWrap: true,
                    itemBuilder: (BuildContext context, int index) {
                      if (type == 'upload') {
                        if (index == photos.length) {
                          return AddContainer();
                        }
                        return RenderAssetsFileImage(
                            key: ValueKey(photos[index].assetEntity.id),
                            file: photos[index],
                            index: index);
                      } else {
                        return CacheNetworkImage(
                            imageUrl: reportData?.content[index] ?? '',
                            width: 112.w,
                            height: 112.h,
                            borderRadius: 8);
                      }
                    },
                    itemCount: type == 'upload'
                        ? photos.length + 1
                        : reportData?.content.length,
                  ),
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}

class RenderAssetsFileImage extends StatelessWidget {
  final UploadModel file;
  final int index;
  const RenderAssetsFileImage(
      {super.key, required this.file, required this.index});

  @override
  Widget build(BuildContext context) {
    final taskDetailProv = Provider.of<TaskDetailProv>(
      context,
      listen: false,
    );
    return Stack(
      clipBehavior: Clip.none,
      children: [
        FutureBuilder(
          future: file.assetEntity.file,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Center(child: CircularProgressIndicator());
            }
            if (snapshot.hasData && snapshot.data != null) {
              return ClipRRect(
                borderRadius: BorderRadius.circular(8).r,
                child: Image.file(
                  snapshot.data!,
                  fit: BoxFit.cover,
                  width: 112.w,
                  height: 112.h,
                  cacheWidth:
                      (112.w * MediaQuery.of(context).devicePixelRatio).toInt(),
                  cacheHeight:
                      (112.h * MediaQuery.of(context).devicePixelRatio).toInt(),
                ),
              );
            }
            return const SizedBox();
          },
        ),
        // Selector<TaskDetailProv, UploadModel>(
        //   selector: (_, prov) => prov.auditUploadPhotos.firstWhere(
        //     (e) => e.assetEntity.id == file.assetEntity.id,
        //     orElse: () => file,
        //   ),
        //   builder: (context, uploadModel, child) {
        //     if (!uploadModel.startUpload || uploadModel.endUpload) {
        //       return const SizedBox();
        //     }
        //     return Positioned.fill(
        //       child: Container(
        //         decoration: BoxDecoration(
        //           color: AppColors.black.withAlpha(100),
        //           borderRadius: BorderRadius.circular(8).r,
        //         ),
        //         padding: EdgeInsets.symmetric(horizontal: 10).r,
        //         child: Column(
        //           crossAxisAlignment: CrossAxisAlignment.center,
        //           mainAxisAlignment: MainAxisAlignment.center,
        //           children: [
        //             ClipRRect(
        //               borderRadius: BorderRadius.circular(4.r),
        //               child: LinearProgressIndicator(
        //                 value: uploadModel.progress / 100,
        //                 minHeight: 7.h,
        //                 backgroundColor: Color(0XFF4d4d4d),
        //                 valueColor:
        //                     AlwaysStoppedAnimation<Color>(AppColors.white),
        //               ),
        //             ),
        //             SizedBox(height: 10.h),
        //             Text(
        //               '${uploadModel.progress}%',
        //               style: customTextStyle(fontSize: 14),
        //             )
        //           ],
        //         ),
        //       ),
        //     );
        //   },
        // ),
        Positioned(
          right: -10.w,
          top: -10.h,
          child: GestureDetector(
            onTap: () => taskDetailProv.removePhotos(file.assetEntity, index),
            child: SvgPicture.asset(
              'assets/icons/icon_upload_remove.svg',
              width: 24.w,
              height: 24.h,
            ),
          ),
        ),
      ],
    );
  }
}

class AddContainer extends StatelessWidget {
  const AddContainer({super.key});
  @override
  Widget build(BuildContext context) {
    final taskDetailProv = Provider.of<TaskDetailProv>(
      context,
      listen: false,
    );
    return GestureDetector(
      onTap: () async {
        List<AssetEntity> res = await Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => MediaPickerPage(
                initialSelectedPhotos: taskDetailProv.auditUploadPhotos
                    .map((e) => e.assetEntity)
                    .toList()),
          ),
        );
        if (res.isNotEmpty) {
          taskDetailProv.setauditUploadPhotos(res);
        }
      },
      child: Container(
        width: 112.w,
        height: 112.h,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Color(0XFF111111),
          borderRadius: BorderRadius.circular(8).r,
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SvgPicture.asset(
              'assets/icons/icon_add.svg',
              width: 12.w,
              height: 12.h,
            ),
            SizedBox(height: 8.h),
            Text(
              'UPLOAD SCREENSHOT',
              style: customTextStyle(fontSize: 14, opacity: 0.5),
              textAlign: TextAlign.center,
            )
          ],
        ),
      ),
    );
  }
}

class SheetContainer extends StatelessWidget {
  final Widget child;
  const SheetContainer({super.key, required this.child});
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: AppColors.sheetBgColor,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
          topRight: Radius.circular(10),
        ),
      ),
      // padding: EdgeInsets.only(left: 17, right: 11, bottom: 30).r,
      padding: EdgeInsets.only(left: 17, right: 11).r,
      child: child,
    );
  }
}

// onPressed: ,
class SheetContainerHeader extends StatelessWidget {
  final List<Widget>? actions;
  final String? title;
  const SheetContainerHeader({super.key, this.actions, this.title});

  @override
  Widget build(BuildContext context) {
    return PreferredSize(
      preferredSize: Size.fromHeight(30.h),
      child: AppBar(
        leading: GestureDetector(
          child: SvgPicture.asset(
            'assets/icons/icon_close.svg',
            width: 24.w,
            height: 24.w,
          ),
          onTap: () => Navigator.pop(context),
        ),
        leadingWidth: 24.w,
        backgroundColor: Colors.transparent,
        title: Text(
          title ?? '',
          style: customTextStyle(fontSize: 16, fontWeight: 600),
        ), // 中间
        actions: actions,
      ),
    );
  }
}
